﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FANUC.DTO;
using Newtonsoft.Json;
using System.Web.Http.Description;

namespace FANUC.Controllers
{
    public class AlarmHistoryInquireController : ApiController
    {
        private FANUCDB db = new FANUCDB();

        /// <summary>
        /// GET: api/ApiAlarmHistory/Robot_YH_No
        /// </summary>
        /// <param name="id">Robot_YH_No</param>
        /// <returns>AlarmHistoryDTO</returns>
        [ResponseType(typeof(AlarmHistoryDtoOut))]
        public IHttpActionResult Get(string id)
        {
            var alarms = db.Alarm_History.Where(a => a.Robot.YH_No == id).ToList();
            if (alarms.Count <= 0)
            {
                return NotFound();
            }
            AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<Alarm_History, AlarmRecordDTO>().ForMember(dest=>dest.Robot_YH_No,src=>src.MapFrom(s=>s.Robot.YH_No)));
            List<AlarmRecordDTO> alarmsDTO = AutoMapper.Mapper.Map<List<AlarmRecordDTO>>(alarms);
            AlarmHistoryDtoOut data = new AlarmHistoryDtoOut();
            data.AlarmRecords = alarmsDTO;
            data.Robot_YH_No = id;

            return Ok(data);
        }

        /// <summary>
        /// GET: api/ApiAlarmHistory/?id=Robot_YH_No&pageNumber=2&pageSize=10
        /// </summary>
        /// <param name="id">Robot_YH_No</param>
        /// <param name="pageNumber">Page Number</param>
        /// <param name="pageSize">Page Size</param>
        /// <returns></returns>
        [ResponseType(typeof(AlarmHistoryDtoOut))]
        public IHttpActionResult Get(string id, int pageNumber, int pageSize)
        {
            var alarms = db.Alarm_History.Where(a => a.Robot.YH_No == id).OrderByDescending(o => o.Time).Skip(pageNumber).Take(pageSize).ToList();
            if (alarms.Count <= 0)
            {
                return NotFound();
            }
            AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<Alarm_History, AlarmRecordDTO>().ForMember(dest => dest.Robot_YH_No, src => src.MapFrom(s => s.Robot.YH_No)));
            List<AlarmRecordDTO> alarmsDTO = AutoMapper.Mapper.Map<List<AlarmRecordDTO>>(alarms);
            AlarmHistoryDtoOut data = new AlarmHistoryDtoOut();
            data.AlarmRecords = alarmsDTO;
            data.Robot_YH_No = id;

            return Ok(data);
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        public string Options()
        {
            return null;
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
